package lyh.hnu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import lyh.hnu.common.CustomException;
import lyh.hnu.common.R;
import lyh.hnu.dto.DishDto;
import lyh.hnu.entity.po.*;
import lyh.hnu.service.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealService setmealService;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Dish> pageinfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Dish::getName, name)
                .orderByDesc(Dish::getUpdateTime);
        Page<Dish> p = dishService.page(pageinfo, queryWrapper);

        Page<DishDto> dishDtoPage = new Page<>();
        //对象拷贝
        BeanUtils.copyProperties(p, dishDtoPage, "records");
        List<Dish> dishRecords = p.getRecords();
        List<DishDto> dishDtoRecords = dishRecords.stream().map(item -> {
            Long categoryId = item.getCategoryId();
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            dishDto.setCategoryName(categoryService.getById(categoryId).getName());
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dishDtoRecords);
        return R.success(dishDtoPage);
    }

    @Transactional
    @DeleteMapping
    public R<String> delete(long... ids) {
        List<Long> dishIdList = new ArrayList<>();
        for (long id : ids) {
            dishIdList.add(id);
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, id);
            dishFlavorService.remove(queryWrapper);
        }
        dishService.removeByIds(dishIdList);
        return R.success("删除菜品成功");
    }

    @GetMapping("/{id}")
    public R<DishDto> selectById(@PathVariable long id) {
        return dishService.selectByIdWithFlavor(id);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        return dishService.updateWithFlavor(dishDto);
    }

    @PostMapping("/status/1")
    public R<String> onSale(@RequestParam List<Long> ids) {
        List<Dish> dishList = dishService.lambdaQuery().in(Dish::getId, ids).list();
        dishList = dishList.stream().map(item -> {
            item.setStatus(1);
            return item;
        }).collect(Collectors.toList());
        dishService.updateBatchById(dishList);
        return R.success("修改售卖状态成功");
    }

    @PostMapping("/status/0")
    public R<String> stopSale(@RequestParam List<Long> ids) {
        List<SetmealDish> setmealDishList = setmealDishService.lambdaQuery()
                .in(SetmealDish::getDishId, ids).list();
        if (!CollectionUtils.isEmpty(setmealDishList)) {
            Set<Long> setmealIdSet = new HashSet<>();
            for (SetmealDish setmealDish : setmealDishList) {
                setmealIdSet.add(setmealDish.getSetmealId());
            }
            Long count = setmealService.lambdaQuery().in(Setmeal::getId, setmealIdSet)
                    .eq(Setmeal::getStatus, 1).count();
            if (count > 0) {
                throw new CustomException("菜品已关联正在售卖中的套餐，无法停售");
            }
        }
        List<Dish> dishList = dishService.lambdaQuery().in(Dish::getId, ids).list();
        dishList = dishList.stream().map(item -> {
            item.setStatus(0);
            return item;
        }).collect(Collectors.toList());
        dishService.updateBatchById(dishList);
        return R.success("修改售卖状态成功");
    }

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<Dish> dishList = dishService.lambdaQuery()
                .eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
                .eq(Dish::getStatus, 1)
                .orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime)
                .list();
        List<DishDto> dishDtoList = dishList.stream().map(item -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            dishDto.setFlavors(dishFlavorService.lambdaQuery().eq(DishFlavor::getDishId, item.getId()).list());
            dishDto.setCategoryName(categoryService.getById(item.getCategoryId()).getName());
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }
}
